import { useChessAI } from './useChessAI'
import { useGameState } from './useGameState'
import type { GameState } from '../types/chess'

interface ExportOptions {
  format: 'PGN' | 'FEN' | 'JSON'
  includeComments?: boolean
  includeEvaluation?: boolean
}

export function useChessNotation() {
  const gameState = useGameState()
  const { findBestMove } = useChessAI()

  const evaluatePosition = (board: (string | null)[][]): number => {
    // 实现评估逻辑
    return 0
  }

  const convertToPGN = (
    moves: string[], 
    result: string | null = null,
    metadata: Record<string, string> = {}
  ): string => {
    const headers = [
      ['Event', metadata.event || '?'],
      ['Site', metadata.site || '?'],
      ['Date', metadata.date || new Date().toISOString().split('T')[0]],
      ['Round', metadata.round || '1'],
      ['White', metadata.white || '?'],
      ['Black', metadata.black || '?'],
      ['Result', result || '*']
    ]

    const headerStr = headers
      .map(([key, value]) => `[${key} "${value}"]`)
      .join('\n')

    const moveStr = moves
      .reduce((acc, move, i) => {
        if (i % 2 === 0) {
          acc.push(`${Math.floor(i/2) + 1}. ${move}`)
        } else {
          acc[acc.length - 1] += ` ${move}`
        }
        return acc
      }, [] as string[])
      .join(' ')

    return `${headerStr}\n\n${moveStr} ${result || '*'}`
  }

  const convertToFEN = (board: (string | null)[][]): string => {
    const rows = board.map(row => {
      let emptyCount = 0
      let fenRow = ''

      row.forEach(piece => {
        if (!piece) {
          emptyCount++
        } else {
          if (emptyCount > 0) {
            fenRow += emptyCount
            emptyCount = 0
          }
          const [color, type] = piece.split('-')
          const pieceChar = getPieceChar(type, color === 'white')
          fenRow += pieceChar
        }
      })

      if (emptyCount > 0) {
        fenRow += emptyCount
      }

      return fenRow
    })

    return rows.join('/')
  }

  const getPieceChar = (type: string, isWhite: boolean): string => {
    const chars: Record<string, string> = {
      king: 'K',
      queen: 'Q',
      rook: 'R',
      bishop: 'B',
      knight: 'N',
      pawn: 'P'
    }
    const char = chars[type] || 'P'
    return isWhite ? char : char.toLowerCase()
  }

  const exportGame = (
    moves: string[],
    board: (string | null)[][],
    options: ExportOptions
  ): string => {
    switch (options.format) {
      case 'PGN':
        return convertToPGN(moves)
      case 'FEN':
        return convertToFEN(board)
      case 'JSON':
        return JSON.stringify({
          moves,
          finalPosition: board,
          evaluation: options.includeEvaluation ? evaluatePosition(board) : undefined
        }, null, 2)
      default:
        return ''
    }
  }

  return {
    convertToPGN,
    convertToFEN,
    exportGame
  }
} 